package main

import (
	"bytes"
	"config"
	"fmt"
	"os"
	"os/exec"
	"simplejson"
	"strings"
)

var (
	UseCurrentDir  bool   //是否使用当前目录下的所有项目
	ProjectsDir    string //当 UseCurrentDir 为 false时，指定项目的目录路径
	GoSublimeFile  string //GoSublime的配置文件路径
	FixProjectDir  string //固定项目目录路径（第三方库）
	ExpectProjects string //排除项目，不需要配置的，多项目中间用`;`隔开

	out               bytes.Buffer
	ExpectProjectList []string
)

func getCurrentPath() (string, error) {
	return os.Getwd()
}

func getCurrentDirList(dirPath string) []string {
	dirList := make([]string, 0)

	f, _ := os.Open(dirPath)
	defer f.Close()

	infoD, _ := f.Readdirnames(0)

	for _, v := range infoD {
		tempDir := dirPath + "\\" + v
		cf, err := os.Stat(tempDir)
		if err != nil {
			fmt.Fprintf(os.Stderr, "os.start err:"+err.Error()+"\n")
			return dirList
		}
		if cf.IsDir() {
			dirList = append(dirList, cf.Name())
		}
	}
	return dirList
}

func getProjectsAllDirPack(dirPath string) string {
	result := "" + FixProjectDir
	dirList := getCurrentDirList(dirPath)
	if len(dirList) > 0 {
		fmt.Fprintf(os.Stderr, "Project List:\n")
	}
	for _, projectName := range dirList {
		projectName = strings.TrimSpace(projectName)
		isFoundSame := false
		for _, expectProjectName := range ExpectProjectList {
			expectProjectName = strings.TrimSpace(expectProjectName)
			if expectProjectName == "" {
				continue
			}
			if expectProjectName == projectName {
				isFoundSame = true
				break
			}
		}
		if !isFoundSame {
			projectDir := dirPath + "\\" + projectName
			result = result + projectDir + ";"
			fmt.Fprintf(os.Stderr, "[Project Name]="+projectName+"  [Project Path]="+projectDir+";\n")
		}
	}
	result = strings.Replace(result, "\\", "\\\\", -1)
	return result
}

func allProjectsPathByLocal() string {
	dirPath, _ := getCurrentPath()

	return getProjectsAllDirPack(dirPath)
}

func allProjectsPathByConfig() string {

	if ProjectsDir == "" {
		return ""
	}

	return getProjectsAllDirPack(ProjectsDir)
}

func GetAllProjectsPath() string {
	if UseCurrentDir {
		return allProjectsPathByLocal()
	} else {
		return allProjectsPathByConfig()
	}
}

func setAllProjectsCommand(allProjectsPath string) bool {
	if GoSublimeFile == "" {
		return false
	}

	dirPath, _ := getCurrentPath()
	opFileName := dirPath + "\\setWindowEnv.vbs"
	f, err := os.OpenFile(opFileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
	if err != nil {
		panic(err)
	}
	os.Remove(opFileName)
	if err != nil {
		panic(err)
	}
	f, err = os.Create(opFileName)
	f.WriteString(`set sysenv=CreateObject("WScript.Shell").Environment("system") `)
	f.WriteString("\n")
	f.WriteString(`sysenv("GOPATH")="` + allProjectsPath + `" `)
	f.Close()

	// rootDir := []byte(allProjectsPath)[0]

	cmd := exec.Command("cmd", "/C"+"", " ", opFileName) //"cd", dirPath, ""
	// cmd := exec.Command("cmd.exe", opFileName)
	cmd.Stdout = &out
	err = cmd.Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Run Command failed.")
	}
	fmt.Fprintf(os.Stderr, "\n"+out.String())

	// cmd = exec.Command("cmd.exe", "cd", dirPath)
	// err = cmd.Run()
	// if err != nil {
	// 	fmt.Fprintf(os.Stderr, "Run Command failed.")
	// }
	// fmt.Fprintf(os.Stderr, "\n"+out.String())

	// cmd = exec.Command("cmd.exe", opFileName)
	// err = cmd.Run()
	// if err != nil {
	// 	fmt.Fprintf(os.Stderr, "Run Command failed.")
	// }
	// fmt.Fprintf(os.Stderr, "\n"+out.String())

	return true
}

func setAllProjectsJson(allProjectsPath string) bool {
	if GoSublimeFile == "" {
		return false
	}

	js, err := simplejson.ParseFile(GoSublimeFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Json Parse Error!")
	}

	allProjectsPath = strings.Replace(allProjectsPath, `\\`, `\`, -1)

	js.Get("env").Set("GOPATH", allProjectsPath)
	saveOK, _ := simplejson.SaveFile(GoSublimeFile, js)
	if !saveOK {
		fmt.Fprintf(os.Stderr, "Json Save Error!")
	}

	js, err = simplejson.ParseFile(GoSublimeFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Json Parse Error!")
	}
	aValue, _ := js.Get("env").Get("GOPATH").String()
	if aValue == allProjectsPath {
		fmt.Fprintf(os.Stderr, "Set Sublime text Success!")
	}

	fmt.Fprintf(os.Stderr, "\n")
	return true
}

func SetAllProjectsPath(allProjectsPath string) bool {

	aResult := setAllProjectsCommand(allProjectsPath)
	if !aResult {
		fmt.Fprintf(os.Stderr, "Set Sublime text Success!")
		return false
	}

	aResult = setAllProjectsJson(allProjectsPath)
	if !aResult {
		return false
	}

	return true
}

func init() {
	dirPath, _ := getCurrentPath()
	aJson := config.JsonConfig{}
	aJsonObj, _ := aJson.Parse(dirPath + "\\ConfigEnv.json")
	if aJsonObj == nil {
		fmt.Println("Json Parse Error!")
	}
	ProjectsDir = aJsonObj.String("projectsDir")
	UseCurrentDir, _ = aJsonObj.Bool("useCurrentDir")
	GoSublimeFile = aJsonObj.String("goSublimeFile")
	FixProjectDir = aJsonObj.String("fixProjectDir")
	ExpectProjects = aJsonObj.String("expectProjects")

	ExpectProjectList = strings.Split(ExpectProjects, ";")
}
